import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { purchaseSwitch, cashierSwitch } from '@/api/home'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { UserState, UserForm, RegisterForm } from '@/types/store'
import { login, logout, getInfo, register,getAppInfo,accountInfo,sellerInfo } from '@/api/login'
import { Module } from 'vuex'

const baseUrl = config.baseUrl
const msgTypes = {
			'您有新订单':1,
			'newOrder':1,
			'您有订单即将超时请确认':2,
			'订单已取消':3, 
			'cancelOrder':3,
			'订单已付款':4,
			'paidOrder':4,
			'其他消息':5
		}
const user: Module<UserState, UserState> = {
  state: {
    token: getToken(),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
		user: storage.get(constant.user),
    permissions: storage.get(constant.permissions),
		socketTask: null,
		websocketData: {}, // 存放从后端接收到的websocket数据
		backgroundMusic: null,
		appInfo:storage.get(constant.appInfo),
		account:{},
		wallets:[],
		seller:{},
		sellerAll:{},
		updateList:null, //用于判断列表元素更新
		isNewOrder:false,
		// 记录最后一次点击时间的元素
		lastTime: new Date().getTime(),
  },
  mutations: {
    SET_TOKEN: (state, token: string) => {
      state.token = token
    },
		SET_NEWORDER: (state, status = false) => {
			state.isNewOrder = status
		},
		SET_APPINFO: (state, appInfo: Object) => {
			state.appInfo = appInfo
			storage.set(constant.appInfo, appInfo)
		},
		SET_UPDATE_LIST: (state, obj = null) => {
			state.updateList = obj
		},
		SET_SELLER: (state, data) => {
			state.sellerAll = data || {}
			state.seller = data?.seller || {}
			state.account = data?.account || {}
			state.wallets = data?.wallets || []
		},
		SET_SELLERINFO: (state, data) => {
			state.seller = state.seller ? {
				...state.seller,
				...data
			} : data
		},
		SET_ACCOUNTINFO: (state, account: Object) => {
			state.account = account
		},
    SET_NAME: (state, name: string) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar: string) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles: Array<string>) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
		SET_USER: (state, user: Object) => {
			state.user = state.user ? {
				...state.user,
				...user
			} : user
			
			storage.set(constant.user, state.user)
		},
    SET_PERMISSIONS: (state, permissions: Array<string>) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
		// SET_WEBSOCKET_DATA (state, data) {
		//   state.websocketData = data
		// }
		
		//点击事件调用，刷新最后一次点击时间
		lastTimeUpdata: (state, lastTime) => {
			state.lastTime = lastTime;
		},

		backgroundMusicPlay(state,type) {
			const urls = {
				1:'/static/music/nyxdd.mp3',
				2:'/static/music/nyddycswqr.mp3',
				3:'/static/music/ddqx.mp3',
				4:'/static/music/ddyfk.mp3',
				5:'/static/music/y1971.mp3'
			}
			const url = urls[type] || "/static/music/y1971.mp3"
			const audioContext = uni.createInnerAudioContext(); //创建雨林鸟播放器对象
			if (audioContext) {
			  try {
					audioContext.onEnded(() => {
					  audioContext.destroy()
					});
					//state.backgroundMusic.destroy()
					//audioContext.sessionCategory = "playback"
					audioContext.src = url
					audioContext.play()
			  } catch (e) {
			    console.log(e)
			  }
			}
		}
  },

  actions: {
    // 登录
    Login({ commit }, userInfo: UserForm) {
      // const username = userInfo.username
      // const password = userInfo.password
      // const code = userInfo.code
      // const uuid = userInfo.uuid
      return new Promise((resolve, reject) => { 
        login(userInfo).then((res: any) => {
		  const data = res.data;
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
	
	// 注册
	Register({ commit }, userInfo: RegisterForm) {
	  return new Promise((resolve, reject) => { 
	    register(userInfo).then((res: any) => {
	      resolve(res)
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},
	
	//获取APP信息
	AppInfo({ commit }) {
	  return new Promise((resolve, reject) => { 
	    getAppInfo().then((res: any) => {
		  commit('SET_APPINFO', res.data)
	      resolve(res)
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},
	
	//获取账户余额信息
	AccountInfo({ commit }) {
	  return new Promise((resolve, reject) => { 
	    accountInfo().then((res: any) => {
		  commit('SET_ACCOUNTINFO', res.data)
	      resolve(res)
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},
	
	//获取销售员信息
	SellerInfo({ commit }) {
	  return new Promise((resolve, reject) => { 
	    sellerInfo().then((res: any) => {
		  commit('SET_SELLER', res.data)
	      resolve(res)
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},
	
	//操作进出货的开关
	switchPurchaseAndCashier({ commit }, obj) {
		const MethodFun = obj?.key == 'cashierSwitch' ? cashierSwitch : purchaseSwitch
		const value = obj?.value ? 1 : 0
	  return new Promise((resolve, reject) => { 
	    MethodFun(value).then((res: any) => {
		  commit('SET_SELLERINFO', {[obj.key]:value})
	      resolve(res)
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},

    // 获取用户信息
    GetInfo({ commit,dispatch }) {
      return new Promise((resolve, reject) => {
        getInfo().then((res: any) => {
					const data=res.data;
          const user = data.user
          const avatar = (user == null || user.avatar == "" || user.avatar == null) ? "/static/images/profile.jpg" : baseUrl + user.avatar
          const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
					//绑定cid 2.0
					//uni.getPushClientId({
					//	success: (res) => {
					//		let push_clientid = res.cid
					//		console.log('客户端推送标识:',push_clientid)
					//	},
					//	fail(err) {
					//		console.log(err)
					//	}
					//});
          if (data.roles && data.roles.length > 0) {
            commit('SET_ROLES', data.roles)
            commit('SET_PERMISSIONS', data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
		  commit('SET_USER', data.user)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
		  // dispatch('AccountInfo')
		  dispatch('SellerInfo')
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then((res) => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
	
	cleanStorage({ dispatch }){
		storage.clean()
		return dispatch('GetInfo')
	},
	
	backgroundMusicInit({ state }, url) {
		console.log("backgroundMusicInit...")
		//state.backgroundMusic = uni.createInnerAudioContext(); //创建雨林鸟播放器对象
		/*
		  "ambient" - 不中止其他声音播放，不能后台播放，静音后无声音；
		  "soloAmbient" - 中止其他声音播放，不能后台播放，静音后无声音；
		  "playback" - 中止其他声音，可以后台播放，静音后有声音。
		 */
		//state.backgroundMusic.sessionCategory = "playback"
		//state.backgroundMusic.obeyMuteSwitch = false;
		//state.backgroundMusic.src = url;
		//state.backgroundMusic.play();
	},
	ReceiveMessageNotice({ commit }, msg) {
		const type = msgTypes[msg] || 5
		commit('backgroundMusicPlay', type)
		if(type == 1 || type == 3){
			commit('SET_NEWORDER', true)
			dispatch('SellerInfo')
		}
	},
	
	websocketInit ({ state, dispatch }) {
		const token = getToken()
		if(token) {
			const url = 'ws://' + config.host + ':' + config.port +'/resource/websocket?Authorization=Bearer '
			+ token + '&clientid=' + config.clientID;
			state.socketTask = uni.connectSocket({
				url, // url是websocket连接ip
				success: () => {
					console.log('websocket连接成功！')
				},
				fail: e => {
					console.log('连接失败' + JSON.stringify(e))
				}
			})
			state.socketTask.onOpen(() => dispatch('websocketOnOpen'))
			state.socketTask.onMessage((res: any) => dispatch('websocketOnMessage', res))
			state.socketTask.onClose(e => dispatch('websocketOnClose'))
			state.socketTask.onError(e => dispatch('websocketOnError'))
		}
	},
	websocketOnOpen ({ commit }) {
		console.log('WebSocket连接正常打开中...！')
	},
	// 收到数据
	websocketOnMessage ({ commit,state,dispatch }, res) {
		console.log('收到服务器内容：' + res.data)
		const message = res.data; 
		try{
			if (message != undefined && message != '' && message.indexOf("{")!=0) {
					uni.showToast({ title: message, icon: 'none' })
					//uni.vibrateShort({
					//	success: ()=>{console.log('VibrateShort success');}
					//});
					const type = msgTypes[message] || 5
					commit('backgroundMusicPlay', type)
					if(type == 1 || type == 3){
						commit('SET_NEWORDER', true)
						dispatch('SellerInfo')
					}
					//if(state.ttsSpeaker) {
					//	state.ttsSpeaker.speak(message, 1);
					//}
			}
		}catch(e){
			
		}
	},
	websocketOnClose ({ commit, dispatch }) {
		console.log('WebSocket连接关闭')
		dispatch('websocketInit');
	},
	websocketOnError ({ commit, dispatch }) {
		console.log('WebSocket连接错误')
		dispatch('websocketInit');
	},
	websocketClose ({ state }) {
		if (!state.socketTask) return
		state.socketTask.close({
			success (res:any) {
				console.log('关闭成功', res)
			},
			fail (err:any) {
				console.log('关闭失败', err)
			}
		})
		state.socketTask = null
	},
	// 发送数据
	websocketSend ({ state }, data) {
		uni.sendSocketMessage({
			data,
			success: res => {
				console.log('发送成功', res)
			},
			fail: e => {
				console.log('发送失败', e)
			}
		})
	}
  }
}

export default user
